/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.DaftarTipsTrik;
import model.TipsTrik;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Nisyyah
 */
public class AddTipsTrik extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private static final String TMP_DIR_PATH = "c:/tmp";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = "Files";
    private File destinationDir;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        tmpDir = new File(TMP_DIR_PATH);
        if (!tmpDir.isDirectory()) {
            throw new ServletException(TMP_DIR_PATH + " is not a directory");
        }
        String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        System.out.println(realPath);
        destinationDir = new File(realPath);
        if (!destinationDir.isDirectory()) {
            throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
        }
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileUploadException, Exception {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        fileItemFactory.setRepository(tmpDir);
        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        String page = request.getParameter("page");
        RequestDispatcher dis = null;
        List<TipsTrik> tipsTriks = new ArrayList<TipsTrik>();
        HttpSession session = request.getSession();
        DaftarTipsTrik dt = new DaftarTipsTrik();
        if (page != null) {
            if (page.equals("upload")) {
                session.removeAttribute("error");
                TipsTrik tipsTrik = new TipsTrik();
                Long idTipsTrik = Long.parseLong(request.getParameter("idTipsTrik"));
                tipsTrik = dt.getTipsTrik(idTipsTrik);
                session.setAttribute("tps", tipsTrik);
                dis = request.getRequestDispatcher("fileTipsTrik.jsp");
                dis.forward(request, response);
            } else if (page.equals("uploaded")) {
                session.removeAttribute("error");
                TipsTrik tipsTrik = new TipsTrik();
                List items = uploadHandler.parseRequest(request);
                Iterator itr = items.iterator();

                while (itr.hasNext()) {
                    FileItem item = (FileItem) itr.next();
                    File file = new File(destinationDir, item.getName());
                    if (file.getName().substring(file.getName().length() - 3, file.getName().length()).equals("swf")
                            || file.getName().substring(file.getName().length() - 3, file.getName().length()).equals("SWF")) {
                        item.write(file);
                        String filepath = DESTINATION_DIR_PATH + "/" + file.getName();
                        tipsTrik = (TipsTrik) session.getAttribute("tps");
                        tipsTrik.setFileTipsTrik(filepath);
                        dt.editTipsTrik(tipsTrik);
                    } else {
                        session.setAttribute("error", "format file harus .swf atau .SWF");
                        dis = request.getRequestDispatcher("fileTipsTrik.jsp");
                        dis.forward(request, response);
                    }
                }
                tipsTriks = dt.getTipsTriks();
                request.setAttribute("tipsTriks", tipsTriks);
                dis = request.getRequestDispatcher("daftarTipsTrik.jsp");
                dis.forward(request, response);
            } else if (page.equals("add")) {
                session.removeAttribute("error");
                dis = request.getRequestDispatcher("tambahTipsTrik.jsp");
                dis.forward(request, response);
            } else if (page.equals("added")) {
                session.removeAttribute("error");
                TipsTrik tipsTrik = new TipsTrik();
                String judulTipsTrik = request.getParameter("judulTipsTrik");
                String keteranganTipsTrik = request.getParameter("keteranganTipsTrik");
                tipsTrik.setJudulTipsTrik(judulTipsTrik);
                tipsTrik.setKeteranganTipsTrik(keteranganTipsTrik);
                if (judulTipsTrik.equals("") || keteranganTipsTrik.equals("")) {
                    session.setAttribute("error", "* masih ada field kosong");
                    dis = request.getRequestDispatcher("tambahTipsTrik.jsp");
                    dis.forward(request, response);
                } else {
                    dt.create(tipsTrik);
                    tipsTriks = dt.getTipsTriks();
                    request.setAttribute("tipsTriks", tipsTriks);
                    dis = request.getRequestDispatcher("daftarTipsTrik.jsp");
                    dis.forward(request, response);
                }
            } else if (page.equals("show")) {
                session.removeAttribute("error");
                if (session.getAttribute("uname") != null) {
                    if (request.getParameter("idTipsTrik") == null) {
                        tipsTriks = dt.getTipsTriks();
                        request.setAttribute("tipsTriks", tipsTriks);
                        dis = request.getRequestDispatcher("daftarTipsTrik.jsp");
                        dis.forward(request, response);
                    } else {
                        Long id = Long.parseLong(request.getParameter("idTipsTrik"));
                        dt.deleteTipsTrik(id);
                        tipsTriks = dt.getTipsTriks();
                        request.setAttribute("tipsTriks", tipsTriks);
                        dis = request.getRequestDispatcher("daftarTipsTrik.jsp");
                        dis.forward(request, response);
                    }
                } else {
                    session.removeAttribute("error");
                    session.setAttribute("error", "anda sudah logout");
                    dis = request.getRequestDispatcher("index.jsp");
                    dis.forward(request, response);
                }
            } else if (page.equals("view")) {
                session.removeAttribute("error");
                tipsTriks = dt.getTipsTriks();
                request.setAttribute("tipsTriks", tipsTriks);
                dis = request.getRequestDispatcher("DaftarTipsTrikUser.jsp");
                dis.forward(request, response);
            }

        } else {
            session.removeAttribute("error");
            dis = request.getRequestDispatcher("index.jsp");
            dis.forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(AddTipsTrik.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(AddTipsTrik.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(AddTipsTrik.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(AddTipsTrik.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
